package com.cloud.wms.http.interceptor;


import com.cloud.wms.http.url.SiteHeader;
import com.cloud.wms.http.url.SiteManager;
import com.cloud.wms.http.url.SiteNameEnum;

import java.io.IOException;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Tanghaibo
 * 2018/4/4
 * description: 动态切换baseUrl
 */

public class BaseUrlInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //获取request的创建者builder
        Request.Builder builder = request.newBuilder();
        //从request中获取headers，通过给定的键url_name
        List<String> headerValues = request.headers(SiteHeader.SITE_HEADER_NAME);
        if ((headerValues != null && headerValues.size() > 0)) {
            //匹配获得新的BaseUrl
            String headerValue = headerValues.get(0);
            HttpUrl newBaseUrl = HttpUrl.parse(SiteManager.getBaseUrl(SiteNameEnum.valueOf(headerValue)));

            if (newBaseUrl == null) {
                return chain.proceed(request);
            }
            //从request中获取原有的HttpUrl实例oldHttpUrl
            HttpUrl oldHttpUrl = request.url();
            //重建新的HttpUrl，修改需要修改的url部分
            HttpUrl newFullUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl.scheme())
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port())
                    .build();
            return chain.proceed(builder.url(newFullUrl).build());
        } else {
            return chain.proceed(request);
        }
    }
}
